<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\adminapi\lists\user;

use app\adminapi\lists\BaseAdminDataLists;
use app\common\enum\user\UserTerminalEnum;
use app\common\enum\MediaSourceEnum;
use app\common\lists\ListsExcelInterface;
use app\common\lists\ListsSearchInterface;
use app\common\model\click\UserCallback;
use app\common\model\promotion\PromotionLink;
use app\common\model\tags\UserTags;
use app\common\model\user\User;
use app\common\service\BuyService;


/**
 * 用户列表
 * Class UserLists
 * @package app\adminapi\lists\user
 */
class PayUserLists extends BaseAdminDataLists implements ListsSearchInterface,ListsExcelInterface
{

    /**
     * @notes 搜索条件
     * @return array
     * @author 段誉
     * @date 2022/9/22 15:50
     */
    public function setSearch(): array
    {
        return [
            '%like%' => ['sn'],
            '='      => ['promotion_link_id', 'platform', 'paynum', 'id','source','is_disable'],
        ];
    }


    /**
     * @notes 获取用户列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author 段誉
     * @date 2022/9/22 15:50
     */
    public function lists(): array
    {
        $oa_id = $this->params['oa_id'] ?? null;
        $ad_id = $this->params['ad_id']??null;
        $tag_id = $this->params['tag_id']??null;

        $where = [];
        $userIdArr = [];
        if (!empty($oa_id)){
            $oaIdUserIdArr = UserCallback::where('oa_id',$oa_id)->column('user_id');
        }
        if (!empty($tag_id)){
            $TagIdUserIdArr = UserTags::where('tag_id','in',$tag_id)->column('user_id');
        }
        if (!empty($oaIdUserIdArr)&&!empty($TagIdUserIdArr)){
            $userIdArr = array_intersect($oaIdUserIdArr, $TagIdUserIdArr);
            //如果没有重复数组，证明没有满足条件用户
            if (empty($userIdArr)){
                $userIdArr = array_push($userIdArr, 0);
            }
        }
        if (!empty($oa_id)){
            if(!empty($oaIdUserIdArr)){
                $userIdArr = $oaIdUserIdArr;
            }else{
                $userIdArr = array_push($userIdArr, 0);
            }
        }
        if (!empty($tag_id)){
            if (!empty($TagIdUserIdArr)){
                $userIdArr = $TagIdUserIdArr;
            }else{
                $userIdArr = array_push($userIdArr, 0);
            }
        }
        if (!empty($userIdArr)){
            $where[] = ['id','in',$userIdArr];
        }
        if (!empty($ad_id)){
            $promotionLinkIdArr = PromotionLink::where('ad_id',$ad_id)->column('id');
            $where[] = ['promotion_link_id','in',$promotionLinkIdArr];
        }
        $query = User::with([
                'usercallback'     => function ($q) {
                    $q->withField('id,user_id,oa_id,brand,model,is_report');
                },
                'promotion'     => function ($q) {
                    $q->withField('id,ad_id');
                },
            ]);
        $lists = $query->where($this->searchWhere)
            ->where($where)
            ->where($this->queryWhere())
            ->field('id,sn,platform,source,promotion_link_id,sex,account,egold,paynum,paymoney,create_time,login_time,is_disable')
            ->limit($this->limitOffset, $this->limitLength)
            ->order(['id' => 'desc'])
            ->select()
            ->toArray();
        foreach ($lists as &$item) {
            $item['source'] = MediaSourceEnum::getSourceDesc($item['source']);
            $item['zb'] = BuyService::getUserZb($item['id']);
            $item['totalUserEgold'] = BuyService::getTotalUserEgold($item['id']);
            $lastLoginTime = strtotime($item['login_time']);
            // 获取当前时间戳
            $currentTimestamp = time();

            // 计算离线时间
            $offlineTime = $currentTimestamp - $lastLoginTime;
//            var_dump($offlineTime);
            // 格式化离线时间
            // 计算离线时间的天、小时、分钟
            $days = floor($offlineTime / (60 * 60 * 24));
            $hours = floor(($offlineTime % (60 * 60 * 24)) / (60 * 60));
            $minutes = floor(($offlineTime % (60 * 60)) / 60);
            $offline_time = '';
            if ($days>0){
                $offline_time = $offline_time.$days . "天 ";
            }
            if ($hours>0){
                $offline_time = $offline_time.$hours . "小时 ";
            }
            if ($minutes>0){
                $offline_time = $offline_time.$minutes . "分钟";
            }
            if ($days==0&&$hours==0&&$minutes==0){
                $offline_time = '刚刚登录';
            }
            $item['offline_time'] = $offline_time;
        }

        return $lists;
    }

    /**
     * @notes 搜索条件
     * @author 段誉
     * @date 2023/2/24 16:08
     */
    public function queryWhere()
    {
        $where = [];
        // 下单时间
        if (!empty($this->params['start_time']) && !empty($this->params['end_time'])) {
            $time    = [strtotime($this->params['start_time']), strtotime($this->params['end_time'])];
            $where[] = ['create_time', 'between', $time];
        }
        $where[] = ['paynum', '>', 0];

        $where[] = ['account', '<>', ''];
        //1 1天内 2:超过一天 3：一周 4:30天 5:90天 6：90天以上
        if ($this->params['start_offline_day']!=''){
            $start_offline_day = time() - ($this->params['start_offline_day'] * 24 * 60 * 60);
            $where[] = ['login_time', '<', $start_offline_day];
        }
        if ($this->params['end_offline_day']!=''){
            $end_offline_day= time() - ($this->params['end_offline_day'] * 24 * 60 * 60);
            $where[] = ['login_time', '>', $end_offline_day];
        }
        if ($this->params['min_paymoney']!=''&&$this->params['max_paymoney']!=''){
            $paymoney    = [$this->params['min_paymoney'], $this->params['max_paymoney']];
            $where[] = ['paymoney', 'between', $paymoney];
        }

        return $where;
    }


    /**
     * @notes 获取数量
     * @return int
     * @author 段誉
     * @date 2022/9/22 15:51
     */
    public function count(): int
    {
        $oa_id = $this->params['oa_id'] ?? null;
        $ad_id = $this->params['ad_id']??null;
        $tag_id = $this->params['tag_id']??null;

        $where = [];
        $userIdArr = [];
        if (!empty($oa_id)){
            $oaIdUserIdArr = UserCallback::where('oa_id',$oa_id)->column('user_id');
        }
        if (!empty($tag_id)){
            $TagIdUserIdArr = UserTags::where('tag_id','in',$tag_id)->column('user_id');
        }
        if (!empty($oaIdUserIdArr)&&!empty($TagIdUserIdArr)){
            $userIdArr = array_intersect($oaIdUserIdArr, $TagIdUserIdArr);
            //如果没有重复数组，证明没有满足条件用户
            if (empty($userIdArr)){
                $userIdArr = array_push($userIdArr, 0);
            }
        }
        if (!empty($oa_id)){
            if(!empty($oaIdUserIdArr)){
                $userIdArr = $oaIdUserIdArr;
            }else{
                $userIdArr = array_push($userIdArr, 0);
            }
        }
        if (!empty($tag_id)){
            if (!empty($TagIdUserIdArr)){
                $userIdArr = $TagIdUserIdArr;
            }else{
                $userIdArr = array_push($userIdArr, 0);
            }
        }
        if (!empty($userIdArr)){
            $where[] = ['id','in',$userIdArr];
        }
        if (!empty($ad_id)){
            $promotionLinkIdArr = PromotionLink::where('ad_id',$ad_id)->column('id');
            $where[] = ['promotion_link_id','in',$promotionLinkIdArr];
        }
        return User::where($where)->where($this->searchWhere)->where($this->queryWhere())->count();
    }


    /**
     * @notes 导出文件名
     * @return string
     * @author 段誉
     * @date 2022/11/24 16:17
     */
    public function setFileName(): string
    {
        return '用户列表';
    }


    /**
     * @notes 导出字段
     * @return string[]
     * @author 段誉
     * @date 2022/11/24 16:17
     */
    public function setExcelFields(): array
    {
        return [
            'sn' => '用户编号',
            'nickname' => '用户昵称',
            'account' => '账号',
            'mobile' => '手机号码',
            'channel' => '注册来源',
            'create_time' => '注册时间',
        ];
    }

}